package com.codeyang.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

@Configuration
@EnableConfigurationProperties(value = WxMsgProperties.class)
public class WxMsgAutoConfiguration {


    private String wxAccessToken;

    @Autowired
    private WxMsgProperties wxMsgProperties;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * token的初始化
     * --- 这样写,可以保证我们 项目一启动的就要执行的 任务,里面的bean优先初始化完成,
     * 这样可以保证,方法执行的必要bean的完整性
     */
    @PostConstruct
    public void initToken() throws InterruptedException {
        refreshWxAccessToken();
    }

    /**
     * 定时任务-- 定时去微信拿 access_token ,微信官方的token 2个小时 7200ms 就失效,1就需要重新获取
     */
    @Scheduled(fixedRate = 7100 * 1000)
    public void refreshWxAccessToken() {
        String appId = wxMsgProperties.getAppId();
        String appSecret = wxMsgProperties.getAppSecret();
        String accessTokenUrl = wxMsgProperties.getAccessTokenUrl();
        // 发一个get请求
        String tokenUrl = String.format(accessTokenUrl, appId, appSecret);
        String wxToken = restTemplate.getForObject(tokenUrl, String.class);
        JSONObject jsonObject = JSON.parseObject(wxToken);
        String accessToken = jsonObject.getString("access_token");
        if (StringUtils.hasText(accessToken)) {
            // 成功拿到token了 我可以存redis TODO 这里可以存到redis中
            wxAccessToken = accessToken;
        } else {
            System.out.println("微信token获取失效");
        }

    }

    public String getWxAccessToken() {
        return wxAccessToken;
    }
}